package cn.xy.base.server.web.security;

import cn.hutool.core.collection.CollUtil;
import cn.xy.base.server.enums.RoleEnum;
import cn.xy.base.server.service.SysPermissionService;
import cn.xy.base.server.web.AdminWebContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限实现
 *
 * @author xy
 */
@Service("validate")
public class PermissionService {

    @Autowired
    private SysPermissionService sysPermissionService;

    /**
     * 连接符
     */
    public static final String SEPARATOR = ",";

    /**
     * 验证用户是否有访问接口的权限
     *
     * @param permissions 权限字符串（sys_permission表的key值）
     * @return 用户是否具备某权限
     */
    public boolean hasPermission(String... permissions) {
        if (permissions == null || permissions.length == 0) {
            return false;
        }
        List<String> permissionList = Arrays.stream(permissions).collect(Collectors.toList());
        int roleId = AdminWebContext.getRoleId();
        if (RoleEnum.isSuperAdmin(roleId)) {
            return true;
        }
        List<String> hasPermissionList = sysPermissionService.keyListByRoleId(roleId);
        if (CollUtil.isEmpty(hasPermissionList)) {
            return false;
        }
        return CollUtil.containsAny(hasPermissionList, permissionList);
    }

}
